package com.doyens.gmall.product.service.impl;

import com.doyens.gmall.product.service.TestService;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class TestServiceImpl implements TestService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RedissonClient redissonClient;

    @Override
    public void testLock() {
        //获取锁对象，默认是可重入锁
        RLock lock = redissonClient.getLock("lock");
        lock.lock();
        String num = redisTemplate.opsForValue().get("num")+"";
        if(num==null) return;
        Integer n = Integer.parseInt(num);
        redisTemplate.opsForValue().set("num",++n);
        lock.unlock();
    }
    //对redis中的num进行累加
    //同步代码块
    //同步方法 锁对象是当前类的对象
    /*public void testLock() {
        //ValueOperations操作string类型的数据
        //hashmap
        //list
        //set   无序
        //zset  有序

        //setIfAbsent 如果redis中没有lock，才向redis中设置值
        String uuid = UUID.randomUUID().toString();
        //如果有lock，就不设置。返回值代表设置成功或者失败
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock",uuid,3, TimeUnit.SECONDS);
        //redis中没有lock，我们加锁成功
        if(lock){
            String num = redisTemplate.opsForValue().get("num")+"";
            if(num==null) return;
            Integer n = Integer.parseInt(num);
            redisTemplate.opsForValue().set("num",++n);
            //释放锁前，需要判断是否是自己的锁
           *//* if(uuid.equals(redisTemplate.opsForValue().get("lock"))){
                redisTemplate.delete("lock");
            }*//*
            //if redis.call('get','lock')== uuid then return redis.call('del','lock') else return 0 end
            //lua 原子性
            String script= "if redis.call('get',KEYS[1])==ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
            DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
            redisScript.setResultType(Long.class);
            redisScript.setScriptText(script);
            redisTemplate.execute(redisScript, Arrays.asList("lock"),uuid);
        }else{
            //说明加锁失败，重试
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            testLock();

        }
    }*/
}
